package cn.lili.modules.lucene;

import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.NativeFSLockFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 17:46 2025/6/23
 */
@Slf4j
@Configuration
public class LuceneDirectoryConfig {

    @Value("${lili.system.lucene.path}")
    private String indexPath;

    /**
     * 创建 Lucene 目录 Bean
     */
    @Bean(destroyMethod = "close")
    public Directory luceneDirectory() throws IOException {
        Path path = Paths.get(indexPath);

        // 确保目录存在
        if (!Files.exists(path)) {
            Files.createDirectories(path);
            log.info("创建 Lucene 索引目录: {}", path);
        }

        // 检查目录是否为空
        if (isDirectoryEmpty(path)) {
            log.info("索引目录为空，将创建空索引");
            createEmptyIndex(path);
        }

        return FSDirectory.open(path, NativeFSLockFactory.INSTANCE);
    }

    private boolean isDirectoryEmpty(Path path) throws IOException {
        try (Stream<Path> entries = Files.list(path)) {
            return !entries.findAny().isPresent();
        }
    }

    private void createEmptyIndex(Path path) throws IOException {
        try (Directory dir = FSDirectory.open(path, NativeFSLockFactory.INSTANCE);
             IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig())) {
            writer.commit();
            log.info("空索引创建成功");
        }
    }
}
